/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.mobao.marshal;

import com.acooly.core.utils.Encodes;
import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiMarshalSupport;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.api.util.XStreams;
import com.acooly.module.openapi.client.provider.mobao.domain.MoBaoNotify;
import com.acooly.module.safety.signature.SignTypeEnum;
import com.acooly.module.safety.support.KeyStoreInfo;
import com.thoughtworks.xstream.XStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author zhangpu
 */
public class MobaoNotifyUnmarshal extends ApiMarshalSupport implements ApiUnmarshal<MoBaoNotify, Map<String, String>> {
    private static final Logger logger = LoggerFactory.getLogger(MobaoNotifyUnmarshal.class);
    private MessageFactory messageFactory;
    protected static KeyStoreInfo keystore = new KeyStoreInfo();

    @SuppressWarnings("unchecked")
    @Override
    public MoBaoNotify unmarshal(Map<String, String> message, String serviceName) {
        try {
            String xml = message.get("message");
            String signature = message.get("signature");
            getSigner(SignTypeEnum.Cert).verify(signature, keystore, xml);
            String xmlMessage = null;
            xmlMessage = new String(Encodes.decodeBase64(xml), "UTF-8");
            logger.info("异步通知 XML:{}", Strings.substringAfter(xmlMessage, "?>"));
            return doUnmarshall(xmlMessage, serviceName);
        } catch (Exception e) {
            throw new ApiClientException("异步通知 解析失败:" + e.getMessage());
        }

    }

    protected MoBaoNotify doUnmarshall(String xml, String serviceName) {
        MoBaoNotify notify = (MoBaoNotify) messageFactory.getNotify(serviceName);
        XStream xstream = XStreams.getXStream();
        xstream.alias("MoBaoAccount", notify.getClass());
        return (MoBaoNotify) xstream.fromXML(xml, notify);
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }

}
